﻿using Digitalmes.Application.Sys.Menus;

namespace Digitalmes.Application.Services.Impl;

internal sealed class UserMenuApplicationService(IRepository<SysUser> userRepo) : IUserMenuApplicationService
{
    public async Task<List<(SysMenuDto menu, string[] roles)>> GetMenusOfUserAsync(long userId)
    {
        var result = await userRepo.AsQueryable()
            .InnerJoin<SysUserRole>((u, ur) => ur.UserId == u.Id)
            .InnerJoin<SysRole>((u, ur, r) => r.Id == ur.RoleId && r.Status == EnabledStatusEnum.Enabled && r.IsDeleted == false)
            .InnerJoin<SysRoleMenu>((u, ur, r, rm) => r.Id == rm.RoleId)
            .InnerJoin<SysMenu>((u, ur, r, rm, m) => m.Id == rm.MenuId)
            .Where((u, ur, r, rm, m) => u.Id == userId)
            .Select((u, ur, r, rm, m) => new { m, r.Code })
            .ToListAsync();

        // 菜单去重
        var menus = result.Select(s => s.m).DistinctBy(u => u.Id).ToList();
        List<(SysMenuDto, string[])> menus2 = new(menus.Count);
        foreach (var menu in menus.Adapt<List<SysMenuDto>>())
        {
            var roles = result.Where(s => s.m.Id == menu.Id).Select(s => s.Code).ToArray();
            menus2.Add((menu, roles));
        }

        return menus2;
    }
}
